﻿using Nest;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Infrastructure.ElasticSearch.ParentChilds
{
    public class ShouldBaseSpecification<T> : ISearchSpecification<ISearchRequest<T>> where T : class
    {
        private readonly IEnumerable<ISearchSpecification<ISearchRequest<T>>> _queries;
        private readonly int _minimumShouldMatch;

        public ShouldBaseSpecification(IEnumerable<ISearchSpecification<ISearchRequest<T>>> queries, int minimumShouldMatch = 1)
        {
            if (queries == null || !queries.Any())
                throw new ArgumentNullException($"{nameof(queries)} cannot be null.");
            _queries = queries;
            _minimumShouldMatch = 0;
        }


        public ISearchRequest<T> IsSatisfiedBy()
        {
            return new SearchDescriptor<T>()
                     .Query(q => q
                         .Bool(b => b
                             .MinimumShouldMatch(_minimumShouldMatch)
                             .Should(
                                 _queries.Select(qu => qu
                                     .IsSatisfiedBy()
                                     .Query
                                 ).ToArray()
                             )
                         )
                     );
        }
    }
}